package com.yun.baymax.base;

import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.yun.baymax.bean.User;
import com.yun.baymax.bean.adapter.LocationInfo;
import com.yun.lib.utils.L;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static cn.bmob.v3.Bmob.getApplicationContext;

/**
 * Created by Administrator on 2017/6/21.
 */

public class LocationHelper {
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationListener mLocationListener;
    private LocationInfo locationInfo;
    private User currentUser;

    private LocationHelper() {
    }

    //单例模式最佳写法
    public static LocationHelper getInstance() {
        return LocationHelperHolder.mInstance;
    }

    public void init() {
        currentUser = BmobUser.getCurrentUser(User.class);
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //可以通过类implement方式实现AMapLocationListener接口，也可以通过创造接口类对象的方法实现
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        L.i("location_success:" + amapLocation.getLatitude() + amapLocation.getLongitude());
                        updateLocation(amapLocation);
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        };
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setInterval(1000 * 60 * 20);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
    }

    private void updateLocation(AMapLocation amapLocation) {
        locationInfo = new LocationInfo();
        locationInfo.setLatitude(amapLocation.getLatitude());
        locationInfo.setLongitude(amapLocation.getLongitude());
        locationInfo.setAddress(amapLocation.getAddress());
        locationInfo.setCity(amapLocation.getCity());
        locationInfo.setDescription(amapLocation.getDescription());
        locationInfo.setDistrict(amapLocation.getDistrict());
        locationInfo.setProvince(amapLocation.getProvince());
        locationInfo.setUsername(currentUser.getHxName());
        //locationInfo.setObjectId(currentUser.getObjectId());此方法无效

        if (TextUtils.isEmpty(currentUser.getLocationId())) {
            save(locationInfo);
        } else
            locationInfo.update(currentUser.getLocationId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        L.i("location_up");
                    } else {
                        L.i(e.getMessage());
                        if (e.getMessage().contains("object not found"))
                            save(locationInfo);
                    }
                }
            });
    }

    private void save(LocationInfo locationInfo) {
        locationInfo.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    L.i("save_ok");
                    currentUser.setLocationId(objectId);
                    currentUser.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e != null)
                                L.i(e.getMessage());
                        }
                    });
                } else L.i(e.getMessage());
            }
        });
    }

    public void startLocation() {
        if (mLocationClient.isStarted())
            mLocationClient.startLocation();
    }

    public void stopLocation() {
        if (!mLocationClient.isStarted())
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        //mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    private static class LocationHelperHolder {
        private static final LocationHelper mInstance = new LocationHelper();
    }


}
